/*
 * DoAnJava3View.java
 */
package doanjava3;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.WriteAbortedException;
import java.util.ArrayList;
import javax.swing.event.TableModelEvent;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListModel;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

/**
 * The application's main frame.
 */
public class DoAnJava3View extends FrameView
{
    //khai bao doi tuong clsDatabase

    private clsDatabase myDatabase;
    //ten duong dan den file can doc/ghi
    private String pathFile = "file.txt";
    //duong dan den file database
    private String pathData = "Database.ser";
    //ten duong dan den imageicon 
    private String pathImageIcon = "resources/table.png";
    //ten cua bang moi duoc tao
    String name = "";
    //list chua danh sach cac bang o che do design
    private ArrayList<JTable> lstTBDes = new ArrayList<JTable>();
    //list chua danh sach cac bang o che do open
    private ArrayList<JTable> lstTBOpe = new ArrayList<JTable>();
    //list chua danh sach cac scrollpane cua moi tabbedpanel
    private ArrayList<JScrollPane> lstCrollP = new ArrayList<JScrollPane>();
    //list chua tinh trang cac bang co duoc luu hay khong (true/false)
    private ArrayList<Boolean> lstIsSaved = new ArrayList<Boolean>();
    //lay ve model cua mainList de lam viec voi cac item cua no
    DefaultListModel modelList = new DefaultListModel();

    public DoAnJava3View(SingleFrameApplication app) throws FileNotFoundException, IOException, ClassNotFoundException
    {
        super(app);
        initComponents();
        myDatabase = new clsDatabase();
        //load Database tu file len bien myDatabase
        myDatabase = loadDatabaseFromFile(pathData);
        lstTBDes = myDatabase.getLstTBDes();
        lstTBOpe = myDatabase.getLstTBOpe();

        //lay ve danh sach cac bang design tu file
//        lstTBDes = getListTableFromFile(pathFile);
//        //chuyen doi danh sach bang design sang danh sach bang thiet ke tuong ung
//        lstTBOpe = getListTableOpen(lstTBDes);
        //lang nghe su kien khi click vao dong cuoi cung cua table thi phat sinh them dong moi
        for (int i = 0; i < lstTBDes.size(); i++)
        {
            newRowListener(lstTBDes.get(i));
            newRowListener(lstTBOpe.get(i));
            //cho moi table lang nghe su kien khi nhan phim KeyUp - KeyDown
            lstTBDes.get(i).addKeyListener(new KeyListener()
            {

                //bat su kien nha phim ra
                public void keyReleased(KeyEvent e)
                {
                    verifyRowPosition(lstTBDes);
                }

                public void keyTyped(KeyEvent e)
                {
                }

                public void keyPressed(KeyEvent e)
                {
                }
            });
            lstTBOpe.get(i).addKeyListener(new KeyListener()
            {

                //bat su kien nha phim ra
                public void keyReleased(KeyEvent e)
                {
                    verifyRowPosition(lstTBOpe);
                }

                public void keyTyped(KeyEvent e)
                {
                }

                public void keyPressed(KeyEvent e)
                {
                }
            });

            System.out.println(lstTBDes.get(i).getName());
        }

        //lay ve danh sach cac bang open tu file

        //hien thi cac bang design len tab panel va list
        viewListTable(lstTBDes);
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener()
        {

            public void actionPerformed(ActionEvent e)
            {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++)
        {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
        {

            public void actionPerformed(ActionEvent e)
            {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener()
        {

            public void propertyChange(java.beans.PropertyChangeEvent evt)
            {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName))
                {
                    if (!busyIconTimer.isRunning())
                    {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                }
                else if ("done".equals(propertyName))
                {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                }
                else if ("message".equals(propertyName))
                {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                }
                else if ("progress".equals(propertyName))
                {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox()
    {
        if (aboutBox == null)
        {
            JFrame mainFrame = DoAnJava3App.getApplication().getMainFrame();
            aboutBox = new DoAnJava3AboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        DoAnJava3App.getApplication().show(aboutBox);
    }

    private JTable createTableDesign()
    {
        //        tbdesign.setModel((DefaultTableModel) createTableDesign().getModel());
        JTable tbdesign = new JTable(1, 2);
        tbdesign.getColumnModel().getColumn(0).setHeaderValue("Field Name");
        tbdesign.getColumnModel().getColumn(1).setHeaderValue("Data Type");
        //        tbdesign.getColumnModel().getColumn(0).setPreferredWidth(190);
        //        tbdesign.getColumnModel().getColumn(1).setPreferredWidth(120);
        JComboBox com = new JComboBox();
        //them combobox kieu du lieu cua cot vao bang moi tao
        com.addItem("Integer");
        com.addItem("String");
        DefaultCellEditor cell = new DefaultCellEditor(com);
        tbdesign.getColumnModel().getColumn(1).setCellEditor(cell);
        return tbdesign;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        mainTabP = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        mainList = new javax.swing.JList();
        mainTollBar = new javax.swing.JToolBar();
        btnAddtable = new javax.swing.JButton();
        btnDeletetable = new javax.swing.JButton();
        btnSavetable = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnGofirst = new javax.swing.JButton();
        btnGoprevious = new javax.swing.JButton();
        lbrow = new javax.swing.JLabel();
        btnGonext = new javax.swing.JButton();
        btnGolast = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        btnDesignTable = new javax.swing.JButton();
        btnOpenTable = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        btnExit = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        TableMenu = new javax.swing.JMenu();
        CreateTableMenuItem = new javax.swing.JMenuItem();
        DeleteTableMenuItem = new javax.swing.JMenuItem();
        SaveTableMenuItem = new javax.swing.JMenuItem();
        RenameTableMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        mainTabP.setName("mainTabP"); // NOI18N
        mainTabP.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mainTabPMouseClicked(evt);
            }
        });
        mainTabP.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                mainTabPKeyReleased(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        mainList.setName("mainList"); // NOI18N
        mainList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mainListMouseClicked(evt);
            }
        });
        mainList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                mainListKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(mainList);

        mainTollBar.setRollover(true);
        mainTollBar.setName("mainTollBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(doanjava3.DoAnJava3App.class).getContext().getResourceMap(DoAnJava3View.class);
        btnAddtable.setIcon(resourceMap.getIcon("btnAddtable.icon")); // NOI18N
        btnAddtable.setText(resourceMap.getString("btnAddtable.text")); // NOI18N
        btnAddtable.setToolTipText(resourceMap.getString("btnAddtable.toolTipText")); // NOI18N
        btnAddtable.setFocusable(false);
        btnAddtable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAddtable.setName("btnAddtable"); // NOI18N
        btnAddtable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAddtable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddtableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnAddtable);

        btnDeletetable.setIcon(resourceMap.getIcon("btnDeletetable.icon")); // NOI18N
        btnDeletetable.setText(resourceMap.getString("btnDeletetable.text")); // NOI18N
        btnDeletetable.setToolTipText(resourceMap.getString("btnDeletetable.toolTipText")); // NOI18N
        btnDeletetable.setFocusable(false);
        btnDeletetable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDeletetable.setName("btnDeletetable"); // NOI18N
        btnDeletetable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDeletetable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletetableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnDeletetable);

        btnSavetable.setIcon(resourceMap.getIcon("btnSavetable.icon")); // NOI18N
        btnSavetable.setText(resourceMap.getString("btnSavetable.text")); // NOI18N
        btnSavetable.setToolTipText(resourceMap.getString("btnSavetable.toolTipText")); // NOI18N
        btnSavetable.setFocusable(false);
        btnSavetable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSavetable.setName("btnSavetable"); // NOI18N
        btnSavetable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSavetable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSavetableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnSavetable);

        jSeparator1.setName("jSeparator1"); // NOI18N
        mainTollBar.add(jSeparator1);

        btnGofirst.setIcon(resourceMap.getIcon("btnGofirst.icon")); // NOI18N
        btnGofirst.setText(resourceMap.getString("btnGofirst.text")); // NOI18N
        btnGofirst.setToolTipText(resourceMap.getString("btnGofirst.toolTipText")); // NOI18N
        btnGofirst.setFocusable(false);
        btnGofirst.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGofirst.setName("btnGofirst"); // NOI18N
        btnGofirst.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGofirst.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGofirstActionPerformed(evt);
            }
        });
        mainTollBar.add(btnGofirst);

        btnGoprevious.setIcon(resourceMap.getIcon("btnGoprevious.icon")); // NOI18N
        btnGoprevious.setText(resourceMap.getString("btnGoprevious.text")); // NOI18N
        btnGoprevious.setToolTipText(resourceMap.getString("btnGoprevious.toolTipText")); // NOI18N
        btnGoprevious.setFocusable(false);
        btnGoprevious.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGoprevious.setName("btnGoprevious"); // NOI18N
        btnGoprevious.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGoprevious.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGopreviousActionPerformed(evt);
            }
        });
        mainTollBar.add(btnGoprevious);

        lbrow.setText(resourceMap.getString("lbrow.text")); // NOI18N
        lbrow.setName("lbrow"); // NOI18N
        mainTollBar.add(lbrow);

        btnGonext.setIcon(resourceMap.getIcon("btnGonext.icon")); // NOI18N
        btnGonext.setText(resourceMap.getString("btnGonext.text")); // NOI18N
        btnGonext.setToolTipText(resourceMap.getString("btnGonext.toolTipText")); // NOI18N
        btnGonext.setFocusable(false);
        btnGonext.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGonext.setName("btnGonext"); // NOI18N
        btnGonext.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGonext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGonextActionPerformed(evt);
            }
        });
        mainTollBar.add(btnGonext);

        btnGolast.setIcon(resourceMap.getIcon("btnGolast.icon")); // NOI18N
        btnGolast.setText(resourceMap.getString("btnGolast.text")); // NOI18N
        btnGolast.setToolTipText(resourceMap.getString("btnGolast.toolTipText")); // NOI18N
        btnGolast.setFocusable(false);
        btnGolast.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGolast.setName("btnGolast"); // NOI18N
        btnGolast.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGolast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGolastActionPerformed(evt);
            }
        });
        mainTollBar.add(btnGolast);

        jSeparator2.setName("jSeparator2"); // NOI18N
        mainTollBar.add(jSeparator2);

        btnDesignTable.setIcon(resourceMap.getIcon("btnDesignTable.icon")); // NOI18N
        btnDesignTable.setText(resourceMap.getString("btnDesignTable.text")); // NOI18N
        btnDesignTable.setToolTipText(resourceMap.getString("btnDesignTable.toolTipText")); // NOI18N
        btnDesignTable.setFocusable(false);
        btnDesignTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDesignTable.setName("btnDesignTable"); // NOI18N
        btnDesignTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDesignTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDesignTableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnDesignTable);

        btnOpenTable.setIcon(resourceMap.getIcon("btnOpenTable.icon")); // NOI18N
        btnOpenTable.setText(resourceMap.getString("btnOpenTable.text")); // NOI18N
        btnOpenTable.setToolTipText(resourceMap.getString("btnOpenTable.toolTipText")); // NOI18N
        btnOpenTable.setFocusable(false);
        btnOpenTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnOpenTable.setName("btnOpenTable"); // NOI18N
        btnOpenTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnOpenTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenTableActionPerformed(evt);
            }
        });
        mainTollBar.add(btnOpenTable);

        jSeparator3.setName("jSeparator3"); // NOI18N
        mainTollBar.add(jSeparator3);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(doanjava3.DoAnJava3App.class).getContext().getActionMap(DoAnJava3View.class, this);
        btnExit.setAction(actionMap.get("quit")); // NOI18N
        btnExit.setIcon(resourceMap.getIcon("btnExit.icon")); // NOI18N
        btnExit.setText(resourceMap.getString("btnExit.text")); // NOI18N
        btnExit.setFocusable(false);
        btnExit.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnExit.setName("btnExit"); // NOI18N
        btnExit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });
        mainTollBar.add(btnExit);

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setName("jButton1"); // NOI18N
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        mainTollBar.add(jButton1);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(mainTabP, javax.swing.GroupLayout.DEFAULT_SIZE, 506, Short.MAX_VALUE))
            .addComponent(mainTollBar, javax.swing.GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addComponent(mainTollBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(mainTabP, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setIcon(resourceMap.getIcon("exitMenuItem.icon")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        exitMenuItem.setPressedIcon(resourceMap.getIcon("exitMenuItem.pressedIcon")); // NOI18N
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        TableMenu.setText(resourceMap.getString("TableMenu.text")); // NOI18N
        TableMenu.setName("TableMenu"); // NOI18N
        TableMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableMenuMouseClicked(evt);
            }
        });

        CreateTableMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        CreateTableMenuItem.setIcon(resourceMap.getIcon("CreateTableMenuItem.icon")); // NOI18N
        CreateTableMenuItem.setText(resourceMap.getString("CreateTableMenuItem.text")); // NOI18N
        CreateTableMenuItem.setName("CreateTableMenuItem"); // NOI18N
        CreateTableMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CreateTableMenuItemActionPerformed(evt);
            }
        });
        TableMenu.add(CreateTableMenuItem);

        DeleteTableMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
        DeleteTableMenuItem.setIcon(resourceMap.getIcon("DeleteTableMenuItem.icon")); // NOI18N
        DeleteTableMenuItem.setText(resourceMap.getString("DeleteTableMenuItem.text")); // NOI18N
        DeleteTableMenuItem.setName("DeleteTableMenuItem"); // NOI18N
        DeleteTableMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteTableMenuItemActionPerformed(evt);
            }
        });
        TableMenu.add(DeleteTableMenuItem);

        SaveTableMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        SaveTableMenuItem.setIcon(resourceMap.getIcon("SaveTableMenuItem.icon")); // NOI18N
        SaveTableMenuItem.setText(resourceMap.getString("SaveTableMenuItem.text")); // NOI18N
        SaveTableMenuItem.setName("SaveTableMenuItem"); // NOI18N
        SaveTableMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveTableMenuItemActionPerformed(evt);
            }
        });
        TableMenu.add(SaveTableMenuItem);

        RenameTableMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0));
        RenameTableMenuItem.setIcon(resourceMap.getIcon("RenameTableMenuItem.icon")); // NOI18N
        RenameTableMenuItem.setText(resourceMap.getString("RenameTableMenuItem.text")); // NOI18N
        RenameTableMenuItem.setName("RenameTableMenuItem"); // NOI18N
        RenameTableMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RenameTableMenuItemActionPerformed(evt);
            }
        });
        TableMenu.add(RenameTableMenuItem);

        menuBar.add(TableMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setIcon(resourceMap.getIcon("aboutMenuItem.icon")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 538, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

private void CreateTableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreateTableMenuItemActionPerformed
// TODO add your handling code here:
    name = JOptionPane.showInputDialog(null, "Enter Table's Name", "New Table", 1);

    if (name == null)
        return;
    else if ("".equals(name))
        JOptionPane.showMessageDialog(null, "Table Name can't null\r\nCreate Table faill.", "Error", 0);
    else
    {
        //tao 1 bang moi o dang thiet ke
        final JTable tbdesign = createTableDesign();
        tbdesign.setName(name + "Design");
        //bang tbdesign bat su kien click vao dong cuoi cung thi phat sinh them dong moi
        newRowListener(tbdesign);
        //bat su kien de xac dinh vi tri cua dong dang duoc chon/tong so dong cua bang
        tbdesign.addKeyListener(new KeyListener()
        {

            public void keyReleased(KeyEvent e)
            {
                //xac dinh vi tri cua dong dang duoc chon/tong so dong cua bang
                verifyRowPosition(lstTBDes);
            }

            public void keyTyped(KeyEvent e)
            {
            }

            public void keyPressed(KeyEvent e)
            {
            }
        });
        //tbdesign lang nghe su kien thay doi gia tri de danh giau la ko luu cho list tinh trang
        tbdesign.getModel().addTableModelListener(new TableModelListener()
        {

            public void tableChanged(TableModelEvent e)
            {
                lstIsSaved.set(mainTabP.getSelectedIndex(), Boolean.FALSE);
            }
        });
        //tao 1 bang rong moi o dang nhap lieu
//        final JTable tbopen = new JTable();
//        tbopen.setName(name + "Design");
//        tbopen.setModel((DefaultTableModel) createTableOpen().getModel());
//        final DefaultTableModel modelopen = (DefaultTableModel)tbopen.getModel();
//        tbopen.addMouseListener(new java.awt.event.MouseAdapter()
//        {
//
//            @Override
//            public void mouseClicked(java.awt.event.MouseEvent e)
//            {
//                if (tbopen.getSelectedRow() == tbopen.getRowCount() - 1)
//                {
//                    modelopen.addRow(new Object[2]);
//                }
//            }
//        });
        //them bang vua tao vao danh sach cac bang thiet ke
        lstTBDes.add(tbdesign);
        //them bang vua tao vao danh sach cac bang nhap lieu
        //them item moi cho mainList
        modelList.add(modelList.getSize(), name);
        mainList.setModel(modelList);
        //them tab moi cho tabpanel
        JScrollPane scrollpane = new JScrollPane();
        scrollpane.setName(name + "ScrollPane");
        scrollpane.setViewportView(tbdesign);
        lstCrollP.add(scrollpane);
        //lay hinh tu resources de add vao tabbedpane
        ImageIcon imageicon = getImageIconFromFile(pathImageIcon);
        //add bang moi, hinh vao tabbedpane
        mainTabP.addTab(name, imageicon, scrollpane);
        //cho con tro chuot chon bang vua tao
        mainList.setSelectedIndex(modelList.size() - 1);
        mainTabP.setSelectedIndex(mainTabP.getTabCount() - 1);
        //them tinh trang da luu (doi voi bang vua tao) vao danh sach tinh trang (save/don't save)
        lstIsSaved.add(true);
    }

}//GEN-LAST:event_CreateTableMenuItemActionPerformed

private void DeleteTableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteTableMenuItemActionPerformed
// TODO add your handling code here:
    //lay ve tat ca vi tri cac item duoc chon
    //JOptionPane.showMessageDialog(null, "Are you sure delete " + mainList., name, busyIconIndex, idleIcon);
    int[] Selecteds = mainList.getSelectedIndices();
    if (Selecteds.length > 0)
    {
        int result = JOptionPane.showConfirmDialog(null, "Are you sure delete selected table(s)?", "Delete table(s)", 0, 3);
        if (result == JOptionPane.YES_OPTION)
        {
            for (int i = Selecteds.length; i > 0; i--)
            {
                //xoa cac item duoc chon trong mainList
                modelList.remove(Selecteds[i - 1]);
                //xoa cac tabPane tuong ung
                mainTabP.remove(Selecteds[i - 1]);
                //xoa bang khoi danh sach cac bang thiet ke
                lstTBDes.remove(Selecteds[i - 1]);
                //xoa cac tinh trang tuong ung cua bang vua xoa
                lstIsSaved.remove(Selecteds[i - 1]);
            }
        }
    }
}//GEN-LAST:event_DeleteTableMenuItemActionPerformed

private void mainListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainListMouseClicked
// TODO add your handling code here:
    mainListEventFunction();
}//GEN-LAST:event_mainListMouseClicked

private void mainTabPMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mainTabPMouseClicked
// TODO add your handling code here:
    mainTabPEventFunction();
}//GEN-LAST:event_mainTabPMouseClicked

private void SaveTableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveTableMenuItemActionPerformed
// TODO add your handling code here:
        //danh dau bang dang mo tren tabpanel da duoc luu (true)
        lstIsSaved.set(mainTabP.getSelectedIndex(), Boolean.TRUE);
        updateTableOpening();
    }

    private void updateTableOpening()
    {
        //cap nhat lai table design dang duoc chon o tab panel
        JScrollPane crollpane = (JScrollPane) mainTabP.getSelectedComponent();
        JTable table = (JTable) crollpane.getViewport().getView();
        int idex = mainTabP.getSelectedIndex();
        String strname = lstTBDes.get(idex).getName().toString();
        table.setName(strname);
}//GEN-LAST:event_SaveTableMenuItemActionPerformed

private void btnAddtableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddtableActionPerformed
// TODO add your handling code here:
    CreateTableMenuItemActionPerformed(evt);
}//GEN-LAST:event_btnAddtableActionPerformed

private void btnDeletetableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletetableActionPerformed
// TODO add your handling code here:
    DeleteTableMenuItemActionPerformed(evt);
}//GEN-LAST:event_btnDeletetableActionPerformed

private void btnSavetableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSavetableActionPerformed
// TODO add your handling code here:
    SaveTableMenuItemActionPerformed(evt);
}//GEN-LAST:event_btnSavetableActionPerformed

private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
// TODO add your handling code here:
    exitMenuItemActionPerformed(evt);
}//GEN-LAST:event_btnExitActionPerformed

private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
// TODO add your handling code here:
    //khong cho phep edit cac bang truoc khi thoat
    for (int i = 0; i < lstTBDes.size(); i++)
    {
        lstTBDes.get(i).setRowSelectionInterval(0, 0);
        lstTBDes.get(i).removeEditor();
        lstTBOpe.get(i).setRowSelectionInterval(0, 0);
        lstTBOpe.get(i).removeEditor();
    }
    //ghi danh sach cac bang design vao file
//    ArrayList<JTable> lsttable = new ArrayList<JTable>();
//    JTable table = null;
//    for (int i = 0; i < mainTabP.getTabCount(); i++)
//    {
//        JScrollPane crollpane = (JScrollPane) mainTabP.getComponentAt(i);
//        table = (JTable) crollpane.getViewport().getComponent(0);
//        lsttable.add(table);
//    }
    //    writeListTableToFile(lsttable, pathFile);
//    lstTBOpe.clear();
//    for (int i = 0; i < lstTBDes.size(); i++)
//    {
//        JTable table = new JTable(2, 3);
//        table.setName("baoanhOpen");
//        lstTBOpe.add(table);
//    }
    //gan cac danh sach cho doi tuong clsDatabase
    myDatabase.setLstTBDes(lstTBDes);
    myDatabase.setLstTBOpe(lstTBOpe);
    saveDatabaseToFile(myDatabase, pathData);
    System.out.println(myDatabase.getLstTBOpe().size());
    //cho mainTabP chon o vi tri tab cuoi cung, de sau sau khoi dong len van nhu vay
    mainTabP.setSelectedIndex(mainTabP.getTabCount() - 1);
}//GEN-LAST:event_exitMenuItemActionPerformed

private void RenameTableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RenameTableMenuItemActionPerformed
// TODO add your handling code here:
    //hien thi hop thoai yeu cau nhap ten moi cho bang da chon
    String newName = JOptionPane.showInputDialog(null, "Enter new name for table: ", "Rename Table", 1);

    if (newName == null)
        return;
    else if ("".equals(newName))
        JOptionPane.showMessageDialog(null, "Table Name can't null\r\nRename Table faill.", "Error", 0);
    else
    {
        //lay chi so item dang duoc chon trong mainList
        int indexSel = mainList.getSelectedIndex();
        //doi ten moi cho item va tab dang chon
        modelList.setElementAt(newName, indexSel);
        mainTabP.setTitleAt(indexSel, newName);
        //doi ten bang trong danh sach bang design
        lstTBDes.get(indexSel).setName(newName + "Design");
    }
}//GEN-LAST:event_RenameTableMenuItemActionPerformed

private void TableMenuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableMenuMouseClicked
// TODO add your handling code here:
    //lay ve so bang dang co
    int nTable = mainList.getModel().getSize();
    System.out.println(nTable);
    //neu ko co bang nao het thi an 1 so chuc nang
    if (nTable == 0)
    {
        DeleteTableMenuItem.setEnabled(false);
        SaveTableMenuItem.setEnabled(false);
        RenameTableMenuItem.setEnabled(false);
    }
    else
    {
        DeleteTableMenuItem.setEnabled(true);
        SaveTableMenuItem.setEnabled(true);
        RenameTableMenuItem.setEnabled(true);
    }
}//GEN-LAST:event_TableMenuMouseClicked

private void btnGolastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGolastActionPerformed
// TODO add your handling code here:
    //lay ve thu tu cua bang dang duoc chon
    int idextablesel = mainTabP.getSelectedIndex();
    //lay ve tong so dong cua bang dang chon
    int totalrow = lstTBDes.get(idextablesel).getRowCount();
    //cho con tro chon dong cuoi cung cua bang
    lstTBDes.get(idextablesel).setRowSelectionInterval(totalrow - 1, totalrow - 1);
    //cap nhat lai vi tri dong dang chon/tong so dong cua bang
    lbrow.setText(totalrow + "/" + totalrow);
    //cho 2 button goNext va goLast an di
    btnGonext.setEnabled(false);
    btnGolast.setEnabled(false);
    //cho 2 button goPrevious va goFirst hien len
    btnGoprevious.setEnabled(true);
    btnGofirst.setEnabled(true);
}//GEN-LAST:event_btnGolastActionPerformed

private void btnGonextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGonextActionPerformed
// TODO add your handling code here:
    goNextFunction();
}//GEN-LAST:event_btnGonextActionPerformed

private void btnGofirstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGofirstActionPerformed
// TODO add your handling code here:
    //lay ve thu tu cua bang dang duoc chon
    int idextablesel = mainTabP.getSelectedIndex();
    //lay ve tong so dong cua bang dang chon
    int totalrow = lstTBDes.get(idextablesel).getRowCount();
    //cho con tro chon dong cuoi cung cua bang
    lstTBDes.get(idextablesel).setRowSelectionInterval(0, 0);
    //cap nhat lai vi tri dong dang chon/tong so dong cua bang
    lbrow.setText(1 + "/" + totalrow);
    //cho 2 button goNext va goLast hien len
    btnGonext.setEnabled(true);
    btnGolast.setEnabled(true);
    //cho 2 button goPrevious va goFirst an di
    btnGoprevious.setEnabled(false);
    btnGofirst.setEnabled(false);
}//GEN-LAST:event_btnGofirstActionPerformed

private void btnGopreviousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGopreviousActionPerformed
// TODO add your handling code here:
    goPreviousFunction();
}//GEN-LAST:event_btnGopreviousActionPerformed

private void mainListKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mainListKeyReleased
// TODO add your handling code here:
    mainListEventFunction();
}//GEN-LAST:event_mainListKeyReleased

private void mainTabPKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_mainTabPKeyReleased
// TODO add your handling code here:
    mainTabPEventFunction();
}//GEN-LAST:event_mainTabPKeyReleased

private void btnDesignTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDesignTableActionPerformed
// TODO add your handling code here:
    //lay ve chi so cua bang dang chon
    int indextablesel = mainList.getSelectedIndex();
    //cho scrollpanel hien thi bang design tuong ung
    lstCrollP.get(indextablesel).setViewportView(lstTBDes.get(indextablesel));
    //xac dinh vi tri cung dong dang chon/tong so dong cua bang hien thoi
    verifyRowPosition(lstTBDes);
    verifyRowPosition(lstTBOpe);
}//GEN-LAST:event_btnDesignTableActionPerformed

private void btnOpenTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenTableActionPerformed
// TODO add your handling code here:
    //lay ve chi so cua bang dang chon
    int indextablesel = mainList.getSelectedIndex();
    //cho scrollpanel hien thi bang open tuong ung
    lstCrollP.get(indextablesel).setViewportView(lstTBOpe.get(indextablesel));
    //xac dinh vi tri cung dong dang chon/tong so dong cua bang hien thoi
    verifyRowPosition(lstTBDes);
    verifyRowPosition(lstTBOpe);
}//GEN-LAST:event_btnOpenTableActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    //khong cho phep edit cac bang truoc khi thoat
    for (int i = 0; i < lstTBDes.size(); i++)
    {
        lstTBDes.get(i).setRowSelectionInterval(0, 0);
        lstTBDes.get(i).removeEditor();
        lstTBOpe.get(i).setRowSelectionInterval(0, 0);
        lstTBOpe.get(i).removeEditor();
    }
}//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem CreateTableMenuItem;
    private javax.swing.JMenuItem DeleteTableMenuItem;
    private javax.swing.JMenuItem RenameTableMenuItem;
    private javax.swing.JMenuItem SaveTableMenuItem;
    private javax.swing.JMenu TableMenu;
    private javax.swing.JButton btnAddtable;
    private javax.swing.JButton btnDeletetable;
    private javax.swing.JButton btnDesignTable;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnGofirst;
    private javax.swing.JButton btnGolast;
    private javax.swing.JButton btnGonext;
    private javax.swing.JButton btnGoprevious;
    private javax.swing.JButton btnOpenTable;
    private javax.swing.JButton btnSavetable;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JLabel lbrow;
    private javax.swing.JList mainList;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JTabbedPane mainTabP;
    private javax.swing.JToolBar mainTollBar;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;

    private void writeListTableToFile(ArrayList<JTable> lsttable, String pathfile)
    {
        clsTable clstable = new clsTable();
        clstable.writeListTableToFile(lsttable, pathfile);
    }

    private ArrayList<JTable> getListTableFromFile(String pathfile) throws FileNotFoundException, IOException, ClassNotFoundException
    {
        clsTable clstable = new clsTable();
        return clstable.getListTableFromFile(pathfile);
    }

    private void viewListTable(ArrayList<JTable> lsttbdes)
    {

        String[] strName = new String[lsttbdes.size()];
        String strname = "";
        int nSize = lsttbdes.size();
        for (int i = 0; i < nSize; i++)
        {
            strName[i] = lsttbdes.get(i).getName();
            strname = strName[i].substring(0, strName[i].length() - 6);
            modelList.add(modelList.getSize(), strname);
            mainList.setModel(modelList);
            //them tab moi cho tabpanel
            JScrollPane scrollpane = new JScrollPane();
            scrollpane.setName(strname + "ScrollPane");
            scrollpane.setViewportView(lsttbdes.get(i));
            lstCrollP.add(scrollpane);
            //lay ImageIcon tu duong dan
            ImageIcon imageicon = getImageIconFromFile(pathImageIcon);
            //them bang vao tabbedpane, vao add ImageIcon vao tabbedpane
            mainTabP.addTab(strname, imageicon, scrollpane);
            //them tinh trang da luu (doi voi bang vua tao) vao danh sach tinh trang (save/don't save)
            lstIsSaved.add(true);
        }
        //cho con tro chuot chon bang vua tao
        mainList.setSelectedIndex(nSize - 1);
        //xac dinh vi tri cua dong dang duoc chon/trong so dong cua bang
        verifyRowPosition(lsttbdes);
    }

    private void verifyRowPosition(ArrayList<JTable> lsttable)
    {
        //lay tong so dong cua bang dang duoc chon
        int totalrow = lsttable.get(mainList.getSelectedIndex()).getRowCount();
        //lay vi tri dong dang duoc cho trong bang
        int indexrowsel = lsttable.get(mainList.getSelectedIndex()).getSelectedRow() + 1;
        lbrow.setText(indexrowsel + "/" + totalrow);
        //neu dang chon o dong dau tien
        if (indexrowsel == 1)
        {
            btnGofirst.setEnabled(false);
            btnGoprevious.setEnabled(false);
            btnGonext.setEnabled(true);
            btnGolast.setEnabled(true);
        }
        else if (indexrowsel == totalrow)
        {
            btnGonext.setEnabled(false);
            btnGolast.setEnabled(false);
            btnGofirst.setEnabled(true);
            btnGoprevious.setEnabled(true);
        }
        else
        {
            btnGonext.setEnabled(true);
            btnGolast.setEnabled(true);
            btnGofirst.setEnabled(true);
            btnGoprevious.setEnabled(true);
        }
        //neu dang chon o dong cuoi cung
    }

    private void newRowListener(final JTable table)
    {
        final DefaultTableModel model = (DefaultTableModel) table.getModel();
        //table se lang nghe su kien click vao dong cuoi cung se them dong moi
        table.addMouseListener(new java.awt.event.MouseAdapter()
        {

            @Override
            public void mouseClicked(java.awt.event.MouseEvent e)
            {
                if (table.getSelectedRow() == table.getRowCount() - 1)
                {
                    model.addRow(new Object[2]);
                }
                //xac dinh vi tri dong duoc chon/trong so dong cua bang
                verifyRowPosition(lstTBDes);
                verifyRowPosition(lstTBOpe);
            }
        });
    }

    private void mainListEventFunction()
    {
        //neu co chon 1 item trem mainList
        if (mainList.getSelectedIndex() != -1)
        {
            //kiem tra xem bang truoc do da luu hay chua
            if (mainTabP.getSelectedIndex() != mainList.getSelectedIndex())
            {
                //neu nhu co thao tac lam thay doi gia tri cua bang ma chua luu lai
                if (lstIsSaved.get(mainTabP.getSelectedIndex()) == false)
                {
                    int result = JOptionPane.showConfirmDialog(null, "Do you save " + name + "'s Table?", "Save Table?", 0, 3);
                    if (result == JOptionPane.YES_OPTION)
                    {
                        //cap nhat lai dua lieu, goi su kien khi nhan nut save table
                        SaveTableMenuItemActionPerformed(null);
                    }
                    else
                    {
                        lstIsSaved.set(mainTabP.getSelectedIndex(), Boolean.TRUE);
//                    lstCrollP.get(mainTabP.getSelectedIndex()).setViewportView(lstTBDes.get(mainTabP.getSelectedIndex()));
//                    JScrollPane crollpane = (JScrollPane)mainTabP.getComponent(mainTabP.getSelectedIndex());
//                    crollpane.setViewportView(lstTBDes.get(mainTabP.getSelectedIndex()-1));
                    }
                }
            }
            int indexsel = mainList.getSelectedIndex();
            //cho tabPanel tuong ung cung chon theo luon
            mainTabP.setSelectedIndex(indexsel);
            //xac dinh vi tri cua dong dang chon/tren tong so dong cua bang
            if ((JTable) lstCrollP.get(indexsel).getViewport().getView() == lstTBDes.get(indexsel))
                verifyRowPosition(lstTBDes);
            else
                verifyRowPosition(lstTBOpe);
        }
    }

    private void mainTabPEventFunction()
    {
        if (mainTabP.getSelectedIndex() != -1)
        {
            int indexsel = mainTabP.getSelectedIndex();
            mainList.setSelectedIndex(indexsel);
            //xac dinh vi tri cua dong dang chon/tren tong so dong cua bang
            if ((JTable) lstCrollP.get(indexsel).getViewport().getView() == lstTBDes.get(indexsel))
                verifyRowPosition(lstTBOpe);
            else
                verifyRowPosition(lstTBDes);
        }
    }

    private void goNextFunction()
    {
        //lay ve thu tu cua bang dang duoc chon
        int idextablesel = mainTabP.getSelectedIndex();
        //lay ve tong so dong cua bang dang chon
        int totalrow = lstTBDes.get(idextablesel).getRowCount();
        //lay ve vi tri cua dong dang duoc chon
        int idexrowsel = lstTBDes.get(idextablesel).getSelectedRow();
        //neu chua chon o dong cuoi dung
        if (idexrowsel != totalrow - 1)
        {
            idexrowsel++;
            lstTBDes.get(idextablesel).setRowSelectionInterval(idexrowsel, idexrowsel);
            //cap nhat lai vi tri dong dang chon/tong so dong cua bang
            lbrow.setText(idexrowsel + 1 + "/" + totalrow);
            //cho 2 button goPrevious va goFirst hien len
            btnGoprevious.setEnabled(true);
            btnGofirst.setEnabled(true);
            //neu da den dong cuoi cung, cho 2 button goNext va goLast an di
            if (idexrowsel == totalrow - 1)
            {
                btnGonext.setEnabled(false);
                btnGolast.setEnabled(false);
            }
        }
    }

    private void goPreviousFunction()
    {
        //lay ve thu tu cua bang dang duoc chon
        int idextablesel = mainTabP.getSelectedIndex();
        //lay ve tong so dong cua bang dang chon
        int totalrow = lstTBDes.get(idextablesel).getRowCount();
        //lay ve vi tri cua dong dang duoc chon
        int idexrowsel = lstTBDes.get(idextablesel).getSelectedRow();
        //neu chua chon o dong dau tien
        if (idexrowsel != 0)
        {
            idexrowsel--;
            lstTBDes.get(idextablesel).setRowSelectionInterval(idexrowsel, idexrowsel);
            //cap nhat lai vi tri dong dang chon/tong so dong cua bang
            lbrow.setText(idexrowsel + 1 + "/" + totalrow);
            //cho 2 button goNext va goLast hien len
            btnGonext.setEnabled(true);
            btnGolast.setEnabled(true);
            //neu da chon den dong dau tien, cho 2 button goPrevious va goFirst an di
            if (idexrowsel == 0)
            {
                btnGoprevious.setEnabled(false);
                btnGofirst.setEnabled(false);
            }
        }
    }

    private ImageIcon getImageIconFromFile(String pathimageicon)
    {
        ImageIcon imageicon = null;
        java.net.URL imgURL = getClass().getResource(pathimageicon);
        if (imgURL != null)
        {
            imageicon = new ImageIcon(this.getClass().getResource(pathimageicon));
        }
        else
        {
            System.err.println("Couldn't find file: " + pathimageicon);
        }
        return imageicon;
    }

    private ArrayList<JTable> getListTableOpen(ArrayList<JTable> lsttbdes)
    {
        ArrayList<JTable> lsttbope = new ArrayList<JTable>();
        for (int i = 0; i < lsttbdes.size(); i++)
        {
            JTable tbopen = convertTableDesToOpe(lsttbdes.get(i));
            //them bang open vao danh sach
            lsttbope.add(tbopen);
        }
        return lsttbope;
    }

    private JTable convertTableDesToOpe(JTable tbdesign)
    {
        int iSize = tbdesign.getRowCount() - 1;
        String lstColName[] = new String[iSize];
        String lstColType[] = new String[iSize];

        for (int i = 0; i < iSize; i++)
        {
            lstColName[i] = tbdesign.getValueAt(i, 0).toString();
            lstColType[i] = tbdesign.getValueAt(i, 1).toString();
        }
        //tao du lieu cho 3 dong
         String rowdata[][] =
        {
            lstColType, lstColType, lstColType
        };
         //tao bang open
         DefaultTableModel defmodel = new DefaultTableModel(rowdata, lstColName);
        JTable tbopen = new JTable(defmodel);
        //cat bo phan ten "Design" va gan vao "Open"
        String strname = tbdesign.getName();
        strname = strname.substring(0, strname.length() - 6);
        strname += "Open";
        tbopen.setName(strname);
        return tbopen;
    }

    private void saveDatabaseToFile(clsDatabase mydatabase, String pathdata)
    {
//        try
//        {
//            //use buffering
//            OutputStream file = new FileOutputStream(pathData);
//            OutputStream buffer = new BufferedOutputStream(file);
//            ObjectOutput output = new ObjectOutputStream(buffer);
//            try
//            {
//                output.writeObject(myDatabase);
//            } finally
//            {
//                output.close();
//            }
//        } catch(NotSerializableException nse){
//            
//        }catch (IOException ex)
//        {
//            Logger.getLogger(DoAnJava3View.class.getPackage().getName()).log(Level.SEVERE, "Cannot perform output.", ex);
//        }
        try
        {
            FileOutputStream fos = new FileOutputStream(pathdata);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(mydatabase);
            System.out.println("hehehehe");
            oos.close();
        } catch (NotSerializableException nse)
        {
            System.out.println(nse.getMessage());
        } catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    private clsDatabase loadDatabaseFromFile(String pathdata) throws IOException, ClassNotFoundException
    {
        clsDatabase database = new clsDatabase();
        try
        {
            FileInputStream fis = new FileInputStream(pathdata);
            ObjectInputStream ois = new ObjectInputStream(fis);
            database = (clsDatabase) ois.readObject();
            ois.close();
        } catch (NotSerializableException nse)
        {
            System.out.println(nse.getMessage());
        } catch (WriteAbortedException wae)
        {
            System.out.println(wae.getMessage());
        }
//        try
//        {
//            //use buffering
//            InputStream file = new FileInputStream(pathdata);
//            InputStream buffer = new BufferedInputStream(file);
//            ObjectInput input = new ObjectInputStream(buffer);
//            try
//            {
//                //deserialize the List
//                database = (clsDatabase) input.readObject();
//            } finally
//            {
//                input.close();
//            }
//        }catch(NotSerializableException nse){
//            System.out.println(nse.getMessage());
//        } catch(WriteAbortedException wae){
//            System.out.println(wae.getMessage());
//        }catch (ClassNotFoundException ex){
//            Logger.getLogger(DoAnJava3View.class.getPackage().getName()).log(Level.SEVERE, "Cannot perform input. Class not found.", ex);
//        } catch (IOException ex){
//            Logger.getLogger(DoAnJava3View.class.getPackage().getName()).log(Level.SEVERE, "Cannot perform input.", ex);
//        }

        return database;
    }
}

class clsTable
{

    void writeListTableToFile(ArrayList<JTable> lsttable, String pathfile)
    {
        int i = 0;
        try
        {
            FileOutputStream fos = new FileOutputStream(pathfile);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            for (i = 0; i < lsttable.size(); i++)
            {
                System.out.println(lsttable.get(i).getName());
                oos.writeObject(lsttable.get(i));
                oos.flush();
            }
            oos.close();
            fos.close();
            fos.close();
        } catch (Exception e)
        {
            System.out.println(e.getMessage().toString());
        }
        System.out.println(lsttable.size());
    }

    ArrayList<JTable> getListTableFromFile(String pathfile) throws FileNotFoundException, IOException, ClassNotFoundException
    {
        ArrayList<JTable> lsttable = new ArrayList<JTable>();
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try
        {
            fis = new FileInputStream(pathfile);
            ois = new ObjectInputStream(fis);
            Object obj = null;
            while ((obj = ois.readObject()) != null)
            {
                if (obj instanceof JTable)
                {
                    final JTable table = (JTable) obj;
                    //them table vao danh sach
                    lsttable.add(table);
                }
            }
        } catch (EOFException e)
        {
            System.out.println("End of File");
        } finally
        {
            try
            {
                if (fis != null)
                {
                    fis.close();
                }
            } catch (IOException ex)
            {
            }
        }
        return lsttable;
    }

    public void newRowListener(final JTable table)
    {
        final DefaultTableModel model = (DefaultTableModel) table.getModel();
        //table se lang nghe su kien click vao dong cuoi cung se them dong moi
        table.addMouseListener(new java.awt.event.MouseAdapter()
        {

            @Override
            public void mouseClicked(java.awt.event.MouseEvent e)
            {
                if (table.getSelectedRow() == table.getRowCount() - 1)
                {
                    model.addRow(new Object[2]);
                }
            }
        });
    }

    public void propertyChange(PropertyChangeEvent evt)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

class clsDatabase implements java.io.Serializable
{
    //list chua danh sach cac bang o che do design

    private ArrayList<JTable> lstTBDes = new ArrayList<JTable>();
    //list chua danh sach cac bang o che do open
    private ArrayList<JTable> lstTBOpe = new ArrayList<JTable>();

    public clsDatabase()
    {
        lstTBDes = null;
        lstTBOpe = null;
    }

    /**
     * @return the lstTBDes
     */
    public ArrayList<JTable> getLstTBDes()
    {
        return lstTBDes;
    }

    /**
     * @param lstTBDes the lstTBDes to set
     */
    public void setLstTBDes(ArrayList<JTable> lstTBDes)
    {
        this.lstTBDes = lstTBDes;
    }

    /**
     * @return the lstTBOpe
     */
    public ArrayList<JTable> getLstTBOpe()
    {
        return lstTBOpe;
    }

    /**
     * @param lstTBOpe the lstTBOpe to set
     */
    public void setLstTBOpe(ArrayList<JTable> lstTBOpe)
    {
        this.lstTBOpe = lstTBOpe;
    }
}